// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

import Common from "../Common";

const {ccclass, property} = cc._decorator;

@ccclass
export default class Profile extends Common {

    @property(cc.Node)
    logoutBtn: cc.Node;

    @property(cc.Node)
    content: cc.Node;

    protected watch = {
        userInfo: (val) => {
            const account = val.account || {}
            const infoNode = this.content.getChildByName('info')
            infoNode.getChildByName('name').getComponent(cc.Label).string = val.user_id || ''
            infoNode.getChildByName('level').getComponent(cc.Label).string = val.invest_level_name || ''
            infoNode.getChildByName('amount').getComponent(cc.Label).string = account.cash_account || '0.00'
        }
    }

    start() {
        // this.logoutBtn.on(cc.Node.EventType.TOUCH_START, this.onLogout, this)
        this.content.children.forEach(item => {
            item.on(cc.Node.EventType.TOUCH_START, this.onItemClick.bind(this, item), this)
        })
    }

    private onItemClick(itemNode: cc.Node) {
        let runSource = true
        switch (itemNode.name) {
            case 'logout': // 注销
                this.onLogout()
                break;
            case 'withdrawal': // 提现申请
                this.node.getChildByName('withdrawDialog').active = true
                break;
            case 'withdrawalRecords': // 提现记录
                cc.director.loadScene('withdrawRecords')
                break;
            case 'bonusLists': // 前往奖金列表
                cc.director.loadScene('bonus')
                break;
            case 'diagram': // 前往我的推荐列表（节点图）
                cc.director.loadScene('users')
                break;
            case 'recharge': // 余额充值申请
                this.node.getChildByName('rechargeDialog').active = true
                break;
            case 'rechargeRecords': // 充值记录
                cc.director.loadScene('rechargeRecords')
                break;
            default:
                runSource = false
        }
        if (runSource) {
            this.onBtnClick()
        }
    }

    async onLogout() {
        try {
            const {message} = await this.http.get('auth/logout')
            this.showToast(message)
            this._data.userInfo = {}
            this._data.hasToken = false
            this._data.currentScene = 'login'
            cc.sys.localStorage.setItem('userToken', '')
        } catch ({message}) {
            this.showToast(message)
        }
    }
}
